library base_pay;

import 'dart:async';
import 'package:base_pay/entity/product/IProductDetails.dart';
import 'package:base_pay/entity/purchase/IPurchaseDetails.dart';
import 'package:base_pay/manager/BasePayManager.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:mybase/base/tool/delay/FFTimeout.dart';
import 'package:mybase/base/tool/pprint/FFLog.dart';
import 'package:mybase/base/tool/time/FFTime.dart';
import 'base_pay_platform_interface.dart';

class PaySuccessInfo {
  String productId;
  String transactionId;
  bool isLifeTime;
  int expires_date_ms;

  PaySuccessInfo({
    required this.productId,
    required this.transactionId,
    this.isLifeTime = false,
    this.expires_date_ms = -1,
  });
}

///项目中，最好单例持有该类
class BasePay {
  late StreamSubscription _subscription;

  Future<String?> getPlatformVersion() {
    return BasePayPlatform.instance.getPlatformVersion();
  }

  ///连接商店
  Future<bool> isAvailable() {
    return BasePayPlatform.instance.isAvailable();
  }

  ///加载商品列表
  ///priorityTrial：       优先返回试用
  ///getAll: 针对android   true返回所有商品，priorityTrial为true,则相同的商品，有试用的排在前面，否则在后面
  Future<List<IProductDetails>> queryProductDetails(
    Set<String> identifiers, {
    bool? priorityTrial = true,
    @deprecated bool? getAll,
    int mill = 15000,
  }) async {
    List<IProductDetails> list = [];
    FFLog.info("开始请求内购信息 ${FFTime.nowSecond()}");
    List<IProductDetails> result = await FFTimeout(
      onTask: Future(() {
        return BasePayPlatform.instance.queryProductDetails(
          identifiers,
          priorityTrial: priorityTrial,
          getAll: getAll,
        );
      }),
      timeOutValue: list,
      mill: mill,
    ).start();
    return result;
  }

  ///开启订阅监听，越早监听越好
  void listen(BasePayDelegate? obj) {
    BasePayManager().delegate = obj;
    final Stream purchaseUpdated = InAppPurchase.instance.purchaseStream;
    _subscription = purchaseUpdated.listen((purchaseDetailsList) {
      BasePayPlatform.instance.listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      //_subscription.cancel();
      obj?.delegate_onDone();
    }, onError: (error) {
      // handle error here.
      obj?.delegate_onError();
    });
  }

  ///发起订阅
  Future<bool> buyNonConsumable(IProductDetails iProductDetails, {String? token}) async {
    return await BasePayPlatform.instance.buyNonConsumable(iProductDetails, token: token);
  }

  ///恢复订阅
  Future<void> restorePurchases({String? token}) async {
    await BasePayPlatform.instance.restorePurchases(token: token);
  }

  ///获取历史订单，iOS获取的是标据
  Future<void> queryHistory({String? token}) async {
    await BasePayPlatform.instance.queryHistory(token: token);
  }

  ///完成交易
  Future<void> completePurchase(IPurchaseDetails iPurchaseDetails) async {
    await BasePayPlatform.instance.completePurchase(iPurchaseDetails);
  }

  ///再次验证，走接口
  /**
   * 返回null：   代表出错了，
   * 返回空数组：  没有订阅
   * 返回[ids]:   订阅期内的商品id数组
   * reTryNum:    正常的一次 + 重试次数 = 总次数
   */
  Future<List<String>?> verifyTheResultsAgain(
    VerifyAgainParam param, {
    int reTryNum = 1,
  }) async {
    return await BasePayPlatform.instance.verifyTheResultsAgain(param, reTryNum: reTryNum);
  }

  ///再次验证，走接口
  /**
   * 返回null：   代表出错了，
   * 返回空数组：  没有订阅
   * 返回[ids]:   订阅期内的商品id数组
   * reTryNum:    正常的一次 + 重试次数 = 总次数
   */
  Future<List<PaySuccessInfo>?> verifyTheResultsAgain2(
    VerifyAgainParam param, {
    int reTryNum = 1,
  }) async {
    return await BasePayPlatform.instance.verifyTheResultsAgain2(param, reTryNum: reTryNum);
  }

  Future<String?> getiOSReceipt() async {
    return await BasePayPlatform.instance.getiOSReceipt();
  }
}

abstract class BasePayDelegate {
  ///监听订单状态
  void delegate_purchaseStatus_purchased(List<IPurchaseDetails> list);

  void delegate_purchaseStatus_errord(IPurchaseDetails iPurchaseDetails);

  void delegate_purchaseStatus_canceled(IPurchaseDetails iPurchaseDetails);

  void delegate_purchaseStatus_pending(IPurchaseDetails iPurchaseDetails);

  void delegate_purchaseStatus_restored(List<IPurchaseDetails> list);

  ///主动拉取历史数据
  Future<void> delegate_androidHistoryPurchases(List<IPurchaseDetails> iList);

  Future<void> delegate_iOSHistoryVerificationData(String data);

  void delegate_listenToEmptyPurchaseList();

  /// 查找历史出错Error: 比如没有网络，没有登录apple id
  /// 回调此函数时，订阅状态需要保持为上一次的状态
  void delegate_queryHistoryError();

  /// 没有历史订单
  void delegate_noHistory();

  ///监听状态
  void delegate_onDone();

  void delegate_onError();

  ///返回验证接口的错误码
  void delegate_apiCode(int? status);
}

///再次验证参数
class VerifyAgainParam {
  ///iOS 票据
  String? iosReceiptData;

  ///iOS 密钥
  String? iosPassword;

  ///时间戳：毫秒
  int? millsecond;

  VerifyAgainParam({
    this.iosReceiptData,
    this.iosPassword,
    this.millsecond,
  });
}

///订阅组
class SubscribeGroup {
  ///订阅组名
  String groupName;

  ///组内所有的订阅IDs,所有组的id都不能相同
  Set ids;

  ///可能有试用,插件外部不要给该值赋值,赋了也不采用
  bool? didFreeTry;

  SubscribeGroup({
    required this.groupName,
    required this.ids,
    this.didFreeTry,
  });
}
